package mspbots.qbd.data.online.profitandloss;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.qbd.common.ResultMsg;
import mspbots.qbd.data.BaseReceiver;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * data.connector.datasync.quickbooks.AccountReceiver
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/5/29
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class OnlineProfitAndLossReceiver extends BaseReceiver {

    private final OnlineProfitAndLossStandardRepository standardRepository;
    private final OnlineProfitAndLossDetailRepository detailRepository;

    @RabbitListener(queues = "quick-books-online.ProfitAndLoss.standard.sync")
    public void processStandard(ResultMsg resultMsg) {
        OnlineProfitAndLossStandard data = OnlineProfitAndLossStandard.builder()
                .tenantId(resultMsg.getTenantId())
                .timePeriod(resultMsg.getEntity().get("timePeriod").textValue())
                .value(resultMsg.getEntity())
                .syncTime(resultMsg.getSyncDate())
                .build();
        this.standardRepository.findByTenantIdAndTimePeriod(data.getTenantId(), data.getTimePeriod())
                .map(oldData -> {
                    data.setId(oldData.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.standardRepository::save).block(Duration.ofSeconds(10));
    }


    @RabbitListener(queues = "quick-books-online.ProfitAndLoss.detail.sync")
    public void processDetail(ResultMsg resultMsg) {
        OnlineProfitAndLossDetail data = OnlineProfitAndLossDetail.builder()
                .tenantId(resultMsg.getTenantId())
                .timePeriod(resultMsg.getEntity().get("timePeriod").asText())
                .value(resultMsg.getEntity())
                .syncTime(resultMsg.getSyncDate())
                .build();

        this.detailRepository.findByTenantIdAndTimePeriod(data.getTenantId(), data.getTimePeriod())
                .map(oldData -> {
                    data.setId(oldData.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.detailRepository::save).block(Duration.ofSeconds(10));
    }

}
